package com.itboy.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itboy.pojo.User;
import com.itboy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
*倚窗听喧嚣
*2020/4/24
*$  web层 查找用户
*/
//添加注解  controller
@RestController
public class UserController {
    //依赖注入service
    @Autowired
    private UserService userService;
    //依赖注入redisTmpilt对象
    @Autowired
    private RedisTemplate redisTemplate;
    //定义查询方法
    @RequestMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }
    @GetMapping("/findAllCache")
    public String findAllCache(){
        //定义返回值
        //判断redis中有没有信息 使用redisTmplit
        String UserStr = (String) redisTemplate.boundValueOps("userAll").get();
        //使用StringUtils工具类中的isEmpty方法判断值是否为空
        if(StringUtils.isEmpty(UserStr)){
          //没有的话存入到redis中
            List<User> users = userService.findAll();
            //把数据转换成json格式,使用objectMapper对象转换
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                UserStr = objectMapper.writeValueAsString(users);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            redisTemplate.boundValueOps("userAll").set(UserStr);
        }
        return UserStr;
    }
}
